package controller

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/kadycui/web/database"
	"github.com/kadycui/web/model"
	"github.com/kadycui/web/utils"
)

type PublishUser struct {
	OpenID     string `json:"open_id"`
	UserID     string `json:"user_id"`
	Password   string `json:"password"`
	ChannelKey string `json:"channel_key"`
}

type UserAuth struct {
	OpenID string `form:"open_id"`
	UserID string `form:"user_id"`
	IdCard string `form:"id_card"`
	Name   string `form:"name"`
}

var log = utils.InitLogger()

func Ping(ctx *gin.Context) {
	id := ctx.Query("id")
	log.Info("这是ping")
	ctx.JSON(200, gin.H{
		"id":   id,
		"code": 0,
		"msg":  "pong",
	})

}

func PublishRegister(ctx *gin.Context) {
	//// 获取原始请求体数据
	//requestBody, err := ctx.GetRawData()
	//if err != nil {
	//	ctx.JSON(400, gin.H{"error": err.Error()})
	//	return
	//}
	//
	//// 打印请求体数据
	//fmt.Println(string(requestBody))

	var pu PublishUser
	if err := ctx.ShouldBindJSON(&pu); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Info(pu.OpenID, pu.UserID, pu.ChannelKey)

	// 加密密码
	encryptedPassword, err := utils.Encrypt([]byte(pu.Password))
	if err != nil {
		panic(err)
	}
	// 打印加密后的密码
	fmt.Println("加密后的密码:", encryptedPassword)

	newPu := model.PublishAccount{
		OpenID:     pu.OpenID,
		UserID:     pu.UserID,
		Password:   encryptedPassword,
		ChannelKey: pu.ChannelKey,
		IP:         ctx.ClientIP(),
	}
	// 这里可以对 user 做进一步处理
	err = database.DB.Create(&newPu).Error
	if err != nil {
		fmt.Println(err)
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  err,
			"code": 1,
		})
	} else {

		//// 解密密码
		//decryptedPassword, err := utils.Decrypt(encryptedPassword)
		//if err != nil {
		//	panic(err)
		//}
		//
		//// 打印解密后的密码
		//fmt.Println("解密后的密码:", string(decryptedPassword))

		ctx.JSON(http.StatusOK, gin.H{"message": "User created", "code": 0})
	}

}

func PublishLogin(ctx *gin.Context) {
	openId := ctx.PostForm("open_id")
	userId := ctx.PostForm("user_id")
	password := ctx.PostForm("password")
	channelKey := ctx.PostForm("channel_key")

	log.Info(openId, userId, password, channelKey)

	var pa model.PublishAccount
	d := make(map[string]string)

	result := database.DB.Where("user_id = ?", userId).First(&pa)
	if result.Error != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  "user not find",
			"data": d,
			"code": 1,
		})
	} else {
		decryptedPassword, err := utils.Decrypt(pa.Password)
		if err != nil {
			panic(err)
		}
		if string(decryptedPassword) == password {
			pa.LoginCount = pa.LoginCount + 1
			d["is_auth"] = pa.IsAuth
			d["is_ok"] = pa.IsOK
			// 保存修改后的数据
			if err := database.DB.Save(&pa).Error; err != nil {
				panic(err)
			}

			ctx.JSON(http.StatusOK, gin.H{
				"code": 0,
				"data": d,
				"msg":  "success!",
			})

		} else {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 1,
				"data": d,
				"msg":  "password error",
			})
		}

	}

}

func PublishAuth(ctx *gin.Context) {
	var ua UserAuth
	d := make(map[string]string)
	var pa model.PublishAccount

	if err := ctx.ShouldBind(&ua); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  "user not find",
			"data": d,
			"code": 1,
		})

	} else {
		log.Info(ua.UserID, ua.OpenID, ua.Name, ua.IdCard)

		result := database.DB.Where("user_id = ?", ua.UserID).First(&pa)
		if result.Error != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"msg":  "user not find",
				"data": d,
				"code": 1,
			})
		} else {
			if utils.IsAdult(ua.IdCard) {
				pa.IsAuth = "Y"
				pa.IsOK = "Y"
				if err := database.DB.Save(&pa).Error; err != nil {
					panic(err)
				}
			}

			d["is_auth"] = pa.IsAuth
			d["is_ok"] = pa.IsOK

			ctx.JSON(http.StatusOK, gin.H{
				"msg":  "success!",
				"data": d,
				"code": 0,
			})

		}

	}

}
